<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
    <script type="text/javascript"
            src="//api.map.baidu.com/api?v=2.0&ak=E4805d16520de693a3fe707cdc962045"></script>
    <script type="text/javascript" src="//api.map.baidu.com/library/Heatmap/2.0/src/Heatmap_min.js"></script>
    <script src="//apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <title>房价热力图</title>
    <style type="text/css">
        ul, li {
            list-style: none;
            margin: 0;
            padding: 0;
            float: left;
        }

        html {
            height: 100%
        }

        body {
            height: 100%;
            margin: 0;
            padding: 0;
            font-family: "微软雅黑";
        }

        #root {
            height: 100%;
            width: 100%;
        }

        #top {
            background: rgba(208, 208, 208, 0.9);
            border-top-left-radius: 5px;
            padding-left: 10px;
            padding-right: 10px;
            /* height: 89px; */
            z-index: 9999;
            position: fixed;
            right: 0;
            bottom: 0;
            color: black;
            font-size: 13px;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        #container {
            height: 100%;
            width: 100%;
        }
    </style>
</head>
<body>
<div id="root">
    <div id="top">
        <div>Tip: 右键可以切换房价和房源 | Code By aWang</div>
    </div>
    <div id="container"></div>
</div>
</body>
</html>
<script type="text/javascript">
    var map = new BMap.Map("container"); // 创建地图实例
    var point = new BMap.Point(116.404, 39.915);
    map.centerAndZoom(point, 12); // 初始化地图，设置中心点坐标和地图级别
    map.enableScrollWheelZoom(); // 允许滚轮缩放
    map.addControl(new BMap.NavigationControl({anchor: BMAP_ANCHOR_TOP_RIGHT}));

    var opts = {
        position: point, // 指定文本标注所在的地理位置
        offset: new BMap.Size(-110, 10) // 设置文本偏移量
    };
    var tipLabel = new BMap.Label("热力图加载需要时间，请稍候...", opts); // 创建文本标注对象
    tipLabel.setStyle({
        color: "blue",
        fontSize: "15px",
        paddingLeft: "10px",
        paddingRight: "10px",
        height: "30px",
        lineHeight: "30px",
        fontFamily: "微软雅黑"
    });
    map.addOverlay(tipLabel);

    var menu = new BMap.ContextMenu();
    var txtMenuItem = [
        {
            text: '房源热力图',
            callback: function () {
                loadHeatmap('count', true)
            }
        },
        {
            text: '房价热力图',
            callback: function () {
                loadHeatmap('price', true)
            }
        }
    ];
    for (var i = 0; i < txtMenuItem.length; i++) {
        menu.addItem(new BMap.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback, 100));
    }
    map.addContextMenu(menu);

    if (!isSupportCanvas()) {
        alert('热力图目前只支持有Canvas支持的浏览器')
    }

    // 详细的参数,可以查看heatmap.js的文档 https://github.com/pa7/heatmap.js/blob/master/README.md //
    // 参数说明如下 //
    /* visible 热力图是否显示,默认为true
     * opacity 热力的透明度,1-100
     * radius 势力图的每个点的半径大小
     * gradient  {JSON} 热力图的渐变区间 . gradient如下所示
     *  {
            .2:'rgb(0, 255, 255)',
            .5:'rgb(0, 110, 255)',
            .8:'rgb(100, 0, 255)'
        }
        其中 key 表示插值的位置, 0~1.
            value 为颜色值.
     */
    var heatmapOverlay = new BMapLib.HeatmapOverlay({"radius": 20});
    // 一定要先 addOverlay //
    map.addOverlay(heatmapOverlay);

    // 是否显示热力图 //
    function openHeatmap() {
        heatmapOverlay.show();
    }

    // 关闭热力图 //
    function closeHeatmap() {
        heatmapOverlay.hide();
    }

    // 设置热力图渐变 //
    function setGradient() {
        var gradient = {
            0: 'rgb(102, 255, 0)',
            0.5: 'rgb(255, 170, 0)',
            1: 'rgb(255, 0, 0)'
        };
        var colors = document.querySelectorAll("input[type='color']");
        colors = [].slice.call(colors, 0);
        colors.forEach(function (ele) {
            gradient[ele.getAttribute("data-key")] = ele.value;
        });
        heatmapOverlay.setOptions({"gradient": gradient});
    }

    // 判断浏览区是否支持canvas //
    function isSupportCanvas() {
        var elem = document.createElement('canvas');
        return !!(elem.getContext && elem.getContext('2d'));
    }

    function getQueryParam() {
        var params = {};
        var tmpArr = location.href.split('?');
        if (tmpArr.length === 2) {
            tmpArr = tmpArr[1].split("&");
            for (var index = 0; index < tmpArr.length; index++) {
                var subArr = tmpArr[index].split('=');
                if (subArr.length === 2) {
                    params[subArr[0]] = subArr[1];
                } else {
                    params[subArr[0]] = ''
                }
            }
        }
        return params;
    }

    function loadHeatmap(type, isSwitch) {
        var params = getQueryParam();
        var city = params.city ? params.city : 'hz';
        $.get("data/" + city + "_" + type + ".json", function (data, status) {
            map.removeOverlay(tipLabel);
            if (status) {
                if (!isSwitch) {
                    // 设置中心点 //
                    var point = new BMap.Point(data.x, data.y);
                    map.centerAndZoom(point, 12);
                }
                // 设置 dataset //
                var points = [];
                heatmapOverlay.setDataSet({data: data.points, max: 100});
                openHeatmap()
            } else {
                alert('加载数据失败')
            }
        });
    }

    closeHeatmap();
    $(document).ready(function () {
        var params = getQueryParam();
        loadHeatmap(params.type ? params.type : 'price', false);
    });
</script>